import Vue from 'vue'
import Router, {Route, RouteConfig} from 'vue-router'
import Global from '@/config/global'

//引入路由组件
Vue.use(Router);

//动态获取组件
const requireComponent = require.context('@/pages', true, /\.(vue)$/);

//路由路径组
const routes: RouteConfig[] = [];

//默认meta
const defaultMeta: VueRouter.Meta = {
   title: Global.pageBaseTitle,
   keepAlive: Global.pageDefaultKeepAlive,
   requiresAuth: Global.pageDefaultRequiresAuth,
};

//动态路由操作之前
routes.push({
   path: '/',
   redirect: Global.indexPagePath,
});

//目录下路由
const dirRoutes: RouteConfig[] = [];

//自动解析路径pages包下vue文件,注册到路由里面
requireComponent.keys().map(fileName => {
   const componentConfig = requireComponent(fileName);
   const componentName = fileName.replace(/^\.\//, '').replace(/\.\w+$/, '');
   const componentNameRe = componentName.replace(/\//g, '-');
   const component = Vue.component(componentNameRe, componentConfig.default || componentConfig);
   const componentOptions = component.options;
   const componentMeta = (componentOptions.meta) ? Object.assign({}, defaultMeta, componentOptions.meta) : defaultMeta;
   const componentParams = (componentOptions.params) ? componentOptions.params : null;
   let componentPath;
   if (componentParams) {
      componentPath = componentName;
      for (let i = 0; i < componentParams.length; i++) {
         componentPath = componentPath + "/:" + componentParams[i];
      }
   } else {
      componentPath = componentName;
   }
   const result: RouteConfig = {
      path: '/' + componentPath,
      name: componentNameRe[0].toLowerCase() + componentNameRe.substring(1),
      meta: componentMeta,
      component,
      children: []
   };
   const arr = componentNameRe.split('-');
   if (arr.length > 1) {//有父级路由子项由此进入
      equivalArray(arr, result);
   } else {//无父级路由子项由此进入
      dirRoutes.push(result);
   }
});

//存储目录生成的结果
dirRoutes.map(val => {
   routes.push(val);
});

//遍历目录生成不同路线的树
function equivalArray(arr: Array<string>, result: RouteConfig) {
   arr.pop();
   let pname = arr.join("-");
   const len = dirRoutes.length;
   for (let i = 0; i < len; i++) {
      recursiveTraverse(dirRoutes[i], (node: RouteConfig) => {
         if (node.name == pname) {//父级匹配
            if (node.children == null) {
               node.children = [];
            }
            node.children.push(result);
         }
      })
   }
}

//递归生成路由树
function recursiveTraverse(node: RouteConfig, action: Function) {
   if (!node || !node.children) {
      return;
   }
   action(node);
   node.children.forEach(function (item: RouteConfig) {
      recursiveTraverse(item, action);
   });
}

//动态路由操作之后
const errorComponent = require('@/errors/' + Global.errorComponentName);
const errorComponentDefault = errorComponent.default;
const errorComponentOptions = errorComponentDefault.options;
const errorComponentMeta = (errorComponentOptions.meta) ? Object.assign({}, defaultMeta, errorComponentOptions.meta) : defaultMeta;
routes.push({
   path: '*',
   meta: errorComponentMeta,
   component: () => import('@/errors/' + Global.errorComponentName)
});

//开发环境打印生成的路由信息
if(process.env.NODE_ENV != 'production'){
   console.log("路由信息",routes)
}

//导出路由对象
const routers = new Router({
   mode: 'history',
   base: process.env.BASE_URL,
   linkActiveClass: 'active',
   linkExactActiveClass: 'active',
   routes: [
      ...routes,
   ],
   fallback: false,
});

//路由跳转前操作,可做权限,路由验证,改HTML属性等等
routers.beforeEach((to: Route, from: Route, next: any): void => {
   document.title = to.meta.title;
   if (to.matched.some(record => record.meta.requiresAuth)) {

   } else {
      next();
   }
});

export default routers;
